package in.muton.edushare.poll.components;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.poll.panels.IPollPanelContainer;

import java.util.Date;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.edushare.common.vo.Poll;

public class AudienceButton extends Button {
	private static final long serialVersionUID = -6103203882199652022L;
	private IModel<Poll> pollModel;
	private EduShareBasePage panel;
	private IPollPanelContainer container;

	public AudienceButton(String id, final IModel<Poll> model,
			EduShareBasePage panel, IPollPanelContainer container) {
		super(id);
		pollModel = model;
		this.panel = panel;
		this.container = container;
		this.add(new Label("caption", new Model<String>() {
			private static final long serialVersionUID = 1L;

			@Override
			public String getObject() {
				if (model.getObject().getStatus() == Poll.POLL_STATUS_DRAFT)
					return "Publish";
				return "Invite People";
			}
		}));
		setDefaultFormProcessing(false);
	}

	@Override
	public void onSubmit() {
		Poll p = pollModel.getObject();
		if (p.getQuestions().size() == 0) {
			panel.setErrorMessage("This poll does not have any questions. "
					+ "Questions are required for a poll to be published.");
			return;
		}
		p.setPollStartDate(new Date());
		p.setStatus(Poll.POLL_STATUS_POLLING);
		container.setPoll(pollModel);
		container.gotoNextPage();
		EduShareSession.get().getSessionORMInterface().commitAllChanges();
	}

	@Override
	public boolean isVisible() {
		if (pollModel == null)
			return true;
		return (pollModel.getObject().getStatus() != Poll.POLL_STATUS_CLOSED);
	}
}
